package com.tanhua.manager.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.manager.domain.Log;
import com.tanhua.manager.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * 监听用户注册登录操作
 * @author anshuai
 * @create 2021-02-24 15:04
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "tanhua-log",consumerGroup = "tanhua-log-group")
public class LogMessageListener implements RocketMQListener<String> {

    @Autowired
    private LogService logService;

    @Override
    public void onMessage(String message) {
        log.info("====处理操作日志消息【开始】====");
        log.info("topic：{}, 接收到的消息内容：{}", "tanhua-log", message);

        //1. 把接收到的json数据，还原成Map对象
        Map map = JSON.parseObject(message, Map.class);
        /**
         * 这么写的原因是因为消息发送过程中是json格式的数据,json是js语法,没有类型Long,所以不能直接强转
         */
        long userId = Long.parseLong(map.get("userId").toString());
        String type = (String) map.get("type");
        String date = (String) map.get("date");

        //2. 把接收到的日志消息，封装成Log对象
        Log logObj = new Log();
        logObj.setUserId(userId);
        logObj.setType(type);
        logObj.setLogTime(date);
        logObj.setCreated(new Date());
        logObj.setUpdated(new Date());
        logObj.setEquipment("小米11");
        logObj.setPlace("内蒙古呼和浩特市");

        //3.把Log对象存储到数据库里
        logService.save(logObj);

        log.info("====处理操作日志消息【完成】====");
    }
}
